package com.x.example.toolbar;

import android.content.Context;
import android.text.TextUtils;

import com.x.uikit.toolbar.XToolbar;
import com.x.uikit.toolbar.XToolbarItem;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class ToolbarRegistry implements XToolbar.IItemCreator {



    private static class Holder {
        final static ToolbarRegistry INSTANCE = new ToolbarRegistry();
    }

    public static ToolbarRegistry get() {
        return Holder.INSTANCE;
    }

    private ToolbarRegistry() {
    }

    private final Map<String, Class<? extends XToolbarItem>> mEmbedClassMap = new ConcurrentHashMap<>();

    public void registerToolbarItem(String token, Class<? extends XToolbarItem> clazz) {
        if (TextUtils.isEmpty(token) || clazz == null || token == null) {
            return;
        }
        mEmbedClassMap.put(token, clazz);
    }

    @Override
    public XToolbarItem createItem(String token, Context context) {
        if (context == null) {
            return null;
        }
        Class<? extends XToolbarItem> clazz = mEmbedClassMap.get(token);
        if (clazz != null) {
            try {
                Constructor<? extends XToolbarItem> constructor = clazz.getConstructor(Context.class,String.class);
                return constructor.newInstance(context,token);
            } catch (NoSuchMethodException e) {
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        }

        return null;
    }
}
